<template>
   <div class="list_container">
      <div style="display: flex; justify-content: space-between">
         <el-breadcrumb
            separator-class="el-icon-arrow-right"
            style="margin-top: 10px; margin-left: 4px"
         >
            <el-breadcrumb-item style="font-size: 16px"
               >系统管理</el-breadcrumb-item
            >
            <el-breadcrumb-item>
               <span style="color: #409eff; font-size: 16px">角色管理</span>
            </el-breadcrumb-item>
         </el-breadcrumb>

         <el-button
            v-if="currentPagePermissionStatusByCurrentUser.createRole"
            style="
               width: 140px;
               line-height: 50px;
               margin-right: 15px;
               margin-top: 14px;
            "
            @click="createRoleDialogShow = true"
         >
            <el-icon style="margin-right: 4px; vertical-align: middle">
               <CirclePlus />
            </el-icon>
            新增角色
         </el-button>
      </div>

      <!-- 角色列表 -->
      <div style="margin-top: 30px">
         <el-table
            style="border-radius: 10px"
            :data="systemRoles"
            stripe
            :header-cell-style="{ height: '60px', fontSize: '16px' }"
            :cell-style="{ height: '60px', fontSize: '14px' }"
            :default-expand-all="false"
         >
            <el-table-column
               prop="num"
               label="序号"
               header-align="center"
               width="100"
               align="center"
            >
            </el-table-column>
            <el-table-column
               prop="roleName"
               label="角色名称"
               header-align="center"
               align="center"
            >
            </el-table-column>
            <el-table-column
               prop="roleDescription"
               label="角色描述"
               header-align="center"
               align="center"
            >
            </el-table-column>
            <el-table-column
               label="操作"
               width="240px"
               header-align="center"
               align="center"
               v-if="currentPagePermissionStatusByCurrentUser.operateRoleList"
            >
               <template v-slot="scope">
                  <el-tooltip
                     effect="dark"
                     content="编辑此角色描述"
                     placement="top-start"
                  >
                     <el-icon
                        @click="editRoleDes(scope.row)"
                        style="
                           font-size: 21px;
                           color: #5a9cf8;
                           cursor: pointer;
                           margin-right: 5px;
                        "
                        ><Edit
                     /></el-icon>
                  </el-tooltip>

                  <el-tooltip
                     effect="dark"
                     placement="top-start"
                     content="编辑此角色权限"
                  >
                     <el-icon
                        style="
                           font-size: 21px;
                           color: #5a9cf8;
                           margin-left: 5px;
                           cursor: pointer;
                        "
                        @click="editRolePermissionDialogOpen(scope.row)"
                     >
                        <EditPen />
                     </el-icon>
                  </el-tooltip>
               </template>
            </el-table-column>
         </el-table>
      </div>

      <!-- 新增角色 -->
      <el-dialog
         v-model="createRoleDialogShow"
         width="500px"
         :show-close="false"
         style="border-radius: 4px"
      >
         <template #header>
            <span style="font-size: 20px; font-weight: 400; margin: 0"
               >新增角色</span
            >
         </template>

         <el-form
            :model="createRoleForm"
            :rules="createRoleRules"
            ref="createRoleFormDom"
         >
            <el-form-item label="角色名称：" prop="roleName">
               <el-input
                  v-model="createRoleForm.roleName"
                  style="width: 80%"
               ></el-input>
            </el-form-item>

            <el-form-item
               label="角色描述："
               prop="roleDescription"
               style="margin-left: 10px"
            >
               <el-input
                  v-model="createRoleForm.roleDescription"
                  style="width: 80%"
               ></el-input>
            </el-form-item>
         </el-form>

         <template #footer>
            <span class="dialog-footer">
               <el-button @click="createRoleDialogShow = false"
                  >取 消</el-button
               >
               <el-button type="primary" @click="createRole()">确 定</el-button>
            </span>
         </template>
      </el-dialog>

      <!-- 编辑角色权限 -->
      <el-dialog
         v-model="editRolePermissionDialogShow"
         width="60%"
         style="border-radius: 4px"
      >
         <template #header>
            <span style="font-size: 18px; float: left"
               >{{ currentRolePermission.roleName }}-权限修改</span
            >
         </template>

         <div style="height: 100%; width: 100%">
            <el-divider content-position="left">权限列表</el-divider>

            <!-- 权限多选框 -->
            <div style="margin-left: 50px; text-align: left">
               <div>
                  <span>系统管理</span>

                  <div style="margin: 15px 0"></div>
                  <span style="margin-left: 15px">用户管理</span>
                  <el-checkbox-group
                     style="margin-left: 30px"
                     v-model="currentRolePermission.permission"
                  >
                     <el-checkbox
                        v-for="permission of systemPermissions.filter(
                           (permission) =>
                              permission.permissionLevel === '系统管理-用户管理'
                        )"
                        :label="permission"
                        :key="permission"
                        style="margin-top: 10px; width: 200px"
                        >{{ permission.permissionName }}
                     </el-checkbox>
                  </el-checkbox-group>

                  <div style="margin: 15px 0"></div>
                  <span style="margin-left: 15px">角色管理</span>
                  <el-checkbox-group
                     style="margin-left: 30px"
                     v-model="currentRolePermission.permission"
                  >
                     <el-checkbox
                        v-for="permission of systemPermissions.filter(
                           (permission) =>
                              permission.permissionLevel === '系统管理-角色管理'
                        )"
                        :label="permission"
                        :key="permission"
                        style="margin-top: 10px; width: 200px"
                        >{{ permission.permissionName }}
                     </el-checkbox>
                  </el-checkbox-group>

                  <div style="margin: 15px 0"></div>
                  <span style="margin-left: 15px">权限管理</span>
                  <el-checkbox-group
                     style="margin-left: 30px"
                     v-model="currentRolePermission.permission"
                  >
                     <el-checkbox
                        v-for="permission of systemPermissions.filter(
                           (permission) =>
                              permission.permissionLevel === '系统管理-权限管理'
                        )"
                        :label="permission"
                        :key="permission"
                        style="margin-top: 10px; width: 200px"
                        >{{ permission.permissionName }}
                     </el-checkbox>
                  </el-checkbox-group>

                  <div style="margin: 15px 0"></div>
                  <span style="margin-left: 15px">操作日志</span>

                  <el-checkbox-group
                     style="margin-left: 30px"
                     v-model="currentRolePermission.permission"
                  >
                     <el-checkbox
                        v-for="permission of systemPermissions.filter(
                           (permission) =>
                              permission.permissionLevel === '系统管理-操作日志'
                        )"
                        :label="permission"
                        :key="permission"
                        style="margin-top: 10px; width: 200px"
                        >{{ permission.permissionName }}
                     </el-checkbox>
                  </el-checkbox-group>
               </div>

               <div style="margin: 15px 0"></div>

               <div>
                  <span>生源地图</span>
                  <el-checkbox-group
                     style="margin-left: 30px"
                     v-model="currentRolePermission.permission"
                  >
                     <el-checkbox
                        v-for="permission of systemPermissions.filter(
                           (permission) =>
                              permission.permissionLevel === '生源地图'
                        )"
                        :label="permission"
                        :key="permission"
                        style="margin-top: 10px; width: 200px"
                        >{{ permission.permissionName }}
                     </el-checkbox>
                  </el-checkbox-group>
               </div>

               <div style="margin: 15px 0"></div>

               <div>
                  <span>学生数据信息</span>
                  <el-checkbox-group
                     style="margin-left: 30px"
                     v-model="currentRolePermission.permission"
                  >
                     <el-checkbox
                        v-for="permission of systemPermissions.filter(
                           (permission) =>
                              permission.permissionLevel === '学生数据信息'
                        )"
                        :label="permission"
                        :key="permission"
                        style="margin-top: 10px; width: 200px"
                        >{{ permission.permissionName }}
                     </el-checkbox>
                  </el-checkbox-group>
               </div>

               <div style="margin: 15px 0"></div>

               <div>
                  <span>学院招生信息</span>
                  <el-checkbox-group
                     style="margin-left: 30px"
                     v-model="currentRolePermission.permission"
                  >
                     <el-checkbox
                        v-for="permission of systemPermissions.filter(
                           (permission) =>
                              permission.permissionLevel === '学院招生信息'
                        )"
                        :label="permission"
                        :key="permission"
                        style="margin-top: 10px; width: 200px"
                        >{{ permission.permissionName }}
                     </el-checkbox>
                  </el-checkbox-group>
               </div>

               <div style="margin: 15px 0"></div>

               <div>
                  <span>招生省份信息</span>
                  <el-checkbox-group
                     style="margin-left: 30px"
                     v-model="currentRolePermission.permission"
                  >
                     <el-checkbox
                        v-for="permission of systemPermissions.filter(
                           (permission) =>
                              permission.permissionLevel === '招生省份信息'
                        )"
                        :label="permission"
                        :key="permission"
                        style="margin-top: 10px; width: 200px"
                        >{{ permission.permissionName }}
                     </el-checkbox>
                  </el-checkbox-group>
               </div>
            </div>
         </div>

         <template #footer>
            <el-button @click="editRolePermissionDialogShow = false"
               >取 消</el-button
            >
            <el-button type="primary" @click="confimChangeRolePermission()"
               >确 定</el-button
            >
         </template>
      </el-dialog>

      <!-- 编辑角色描述信息 -->
      <el-dialog
         v-model="eidtRoleDesDialogShow"
         width="25%"
         :showClose="false"
         style="border-radius: 4px"
      >
         <template #header>
            <span style="font-size: 18px">{{ editRoleDesForm.roleName }}</span>
         </template>

         <el-form :model="editRoleDesForm">
            <el-form-item
               style="margin-left: -28px"
               label="角色描述"
               label-width="100"
               prop="telephone"
            >
               <el-input
                  style="width: 380px"
                  v-model="editRoleDesForm.roleDescription"
                  placeholder="请输入角色描述："
               ></el-input>
            </el-form-item>
         </el-form>

         <template #footer>
            <el-button @click="eidtRoleDesDialogShow = false">取 消</el-button>
            <el-button type="primary" @click="confimEditRoleDes()"
               >修 改</el-button
            >
         </template>
      </el-dialog>
   </div>
</template>

<script>
import $axios from "@/axios";
import { useStore } from "vuex";
import router from "@/rooter";
import { onMounted, reactive, ref, watch } from "vue";
import { ElMessage } from "element-plus";

export default {
   name: "角色管理",
   setup() {
      const store = useStore();

      // 系统所有角色
      let systemRoles = ref([]);

      // 系统所有权限
      let systemPermissions = ref([]);

      // 当前页当前用户权限
      let currentPagePermissionStatusByCurrentUser = reactive({
         roleManagementPageShow: false,
         createRole: false,
         operateRoleList: false,
      });

      // ===============================

      // 控制新增角色窗口是否显示
      let createRoleDialogShow = ref(false);

      // 新增角色表单
      let createRoleForm = reactive({
         roleName: "",
         roleDescription: "",
      });

      // 新增角色表单dom
      const createRoleFormDom = ref(null);

      // 输入角色名的限制规则
      const createRoleRules = {
         roleName: [
            { required: true, message: "请输入角色名称", trigger: "blur" },
            {
               min: 1,
               max: 10,
               message: "长度在 1 到 10 个字符",
               trigger: "blur",
            },
         ],
      };

      // 新增角色请求
      function createRole() {
         createRoleFormDom.value.validate((valid) => {
            if (valid) {
               $axios.post("/role/createRole", createRoleForm).then((resp) => {
                  ElMessage({
                     type: "success",
                     message: "角色添加成功",
                     duration: 1000,
                  });

                  setTimeout(() => {
                     window.location.reload();
                  }, 1000);
               });
            } else {
               ElMessage({
                  type: "error",
                  message: "请填写角色名称",
                  duration: 2000,
               });
            }
         });
      }

      // ===============================

      // 控制编辑角色权限的dialog是否显示
      let editRolePermissionDialogShow = ref(false);

      // 当前点击角色的权限
      let currentRolePermission = reactive({
         roleId: "",
         roleName: "",
         permission: [],
      });

      // 编辑权限弹窗打开事件
      function editRolePermissionDialogOpen(row) {
         editRolePermissionDialogShow.value = true;

         currentRolePermission.roleId = row.id;
         currentRolePermission.roleName = row.roleName;
         currentRolePermission.permission = row.systemPermissions;

         // 获取系统所有权限
         $axios.get("/permission/allPermissions").then((resp) => {
            systemPermissions.value = resp.data.data;
         });
      }

      // 确认修改角色权限
      function confimChangeRolePermission() {
         // 参数：当前用户权限,当前用户id
         $axios
            .post("/role/updateRolePermission", currentRolePermission)
            .then(() => {
               ElMessage({
                  type: "success",
                  message: "角色权限修改成功",
                  duration: 1000,
               });

               setTimeout(() => {
                  window.location.reload();
               }, 1000);

               editRolePermissionDialogShow.value = false;
            });
      }

      // ===============================

      // 控制编辑角色描述信息dialog是否显示
      let eidtRoleDesDialogShow = ref(false);

      // 角色描述修改表单
      let editRoleDesForm = reactive({
         roleId: "",
         roleName: "",
         roleDescription: "",
         roleDescriptionOrigin: "",
      });

      // 修改角色描述
      function editRoleDes(row) {
         eidtRoleDesDialogShow.value = true;

         editRoleDesForm.roleId = row.id;
         editRoleDesForm.roleName = row.roleName;
         editRoleDesForm.roleDescription = row.roleDescription;
         editRoleDesForm.roleDescriptionOrigin = row.roleDescription;
      }

      // 确认修改
      function confimEditRoleDes() {
         // 如果角色描述未发生改变，则直接关闭窗口
         if (
            editRoleDesForm.roleDescriptionOrigin ===
            editRoleDesForm.roleDescription
         ) {
            eidtRoleDesDialogShow.value = false;
            return;
         }

         // 发送请求，修改角色描述
         $axios
            .post("/role/updateRoleDescription", editRoleDesForm)
            .then(() => {
               ElMessage({
                  type: "success",
                  message: "角色描述修改成功",
                  duration: 1000,
               });

               setTimeout(() => {
                  window.location.reload();
               }, 1000);
            });
      }

      // 等待vuex中的userPermission准备好
      function waitForPermissions() {
         return new Promise((resolve) => {
            store.watch(
               () => store.state.currentLoginUser.permissions,
               (newValue) => {
                  // 权限：
                  // 1.新增角色
                  // 2.操作角色列表
                  if (newValue) {
                     newValue.forEach((permission) => {
                        if (
                           permission.permissionPath ===
                           "/systemManagement/roleManagement"
                        ) {
                           currentPagePermissionStatusByCurrentUser.roleManagementPageShow = true;
                        }

                        if (permission.permissionPath === "/systemManagement/roleManagement/createRole") {
                           currentPagePermissionStatusByCurrentUser.createRole = true;
                        }

                        if (
                           permission.permissionPath === "/systemManagement/roleManagement/operateRole"
                        ) {
                           currentPagePermissionStatusByCurrentUser.operateRoleList = true;
                        }
                     });

                     // 将 Promise 状态改为已完成
                     resolve();
                  }
               },
               {
                  immediate: true, // 立即监听
               }
            );
         });
      }

      onMounted(async () => {
         await waitForPermissions();

         if (!currentPagePermissionStatusByCurrentUser.roleManagementPageShow) {
            ElMessage({
               type: "error",
               message: "用户无权限",
               duration: 1500,
            });
            router.go(-1);
            return;
         }

         // 获取系统所有角色
         $axios.get("/role/allRole").then((resp) => {
            for (let i = 0; i < resp.data.data.length; i++) {
               resp.data.data[i].num = i + 1;
            }

            systemRoles.value = resp.data.data;
         });
      });

      return {
         systemRoles,
         createRoleForm,
         createRoleDialogShow,
         createRoleRules,
         createRoleFormDom,
         createRole,
         editRolePermissionDialogShow,
         editRolePermissionDialogOpen,
         systemPermissions,
         currentRolePermission,
         confimChangeRolePermission,
         eidtRoleDesDialogShow,
         editRoleDes,
         confimEditRoleDes,
         editRoleDesForm,
         currentPagePermissionStatusByCurrentUser,
      };
   },
};
</script>

<style>
</style>